//
//  MKOAuthViewController.swift
//  101weibo
//
//  Created by 劢克科技 on 2019/1/24.
//  Copyright © 2019 劢克科技. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class MKOAuthViewController: UIViewController {
    
    lazy var webV: UIWebView = UIWebView()

    override func viewDidLoad() {
        super.viewDidLoad()

        webV.delegate = self
        
        setUI()
        requestUrl()
    }
}

//MARK: - UI
extension MKOAuthViewController {
    private func setUI() {
        webV.backgroundColor = UIColor.white
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(fillUserInfo))
        navigationItem.title = "登录页面"
        
        view.addSubview(webV)
        webV.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
    }
}

//MARK: - event
extension MKOAuthViewController {
    private func requestUrl() {
        let urlString = "\(LoginUrl)?client_id=\(AppKey)&redirect_uri=\(RedirectUrl)"
        guard let url = URL(string: urlString) else {
            return
        }
        webV.loadRequest(URLRequest(url: url))
    }
    
    @objc private func close() {
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func fillUserInfo() {
        let jsCode = "document.getElementById('userId').value='13261675306';document.getElementById('passwd').value='5dwbmmshi'"
        webV.stringByEvaluatingJavaScript(from: jsCode)
    }
}

//MARK: - WebView Delegate
extension MKOAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        
        //判断网址是否含有code。如果有 取出来；没有 加载页面。
        guard let url = request.url else {
            return true
        }
        
        let urlString = url.absoluteString
        
        guard urlString.contains("code=") else {
            return true
        }
        
        guard let code = urlString.components(separatedBy: "code=").last else {
            return true
        }
        
        return false
    }
}
